import hashlib

block_size=4096000
storage_path="/home/squat/tmp/2012-08-05/test/storage/"

def hash(block):
	m = hashlib.sha1()
	m.update(block)
	return m.hexdigest()

def need_for_block(offset, hash1):
	block_nr = int(offset / block_size)

	try:
		with open(storage_path + str(block_nr) +".hash", "rb") as f:
			hash2 = f.read(40)
	except:
		hash2 = ""
	
	return not (hash1 == hash2)

def store_block(offset, block):
	block_nr = int(offset / block_size)

	if need_for_block(offset, hash(block)):
		with open(storage_path + str(block_nr) +".block", "wb") as fb:
			fb.write(block)

		with open(storage_path + str(block_nr) +".hash", "wb") as fh:
			fh.write(hash(block))
